import { round } from "lodash"
import { Vertices } from "../types"

type Rect = { width: number, height: number }

/** 获取最小点 */
export function getMinPoint(vertices: Vertices) {
  let [maxX, maxY] = vertices[0]
  let [minX, minY] = vertices[0]
  vertices.forEach((vertex) => {
    const [x, y] = vertex
    if (minX > x) {
      minX = x
    }
    if (minY > y) {
      minY = y
    }
    if (x > maxX) {
      maxX = x
    }
    if (y > maxY) {
      maxY = y
    }
  })
  return { x: minX, y: minY }
}

export function getRectFormVertices(vertices: Vertices): Rect {
  // let rect: Rect = { width: 0, height: 0 }
  let [maxWidth, maxHeight] = vertices[0]
  let [minWidth, minHeight] = vertices[0]
  vertices.forEach((vertex) => {
    const [x, y] = vertex
    if (minWidth > x) {
      minWidth = x
    }
    if (minHeight > y) {
      minHeight = y
    }
    if (x > maxWidth) {
      maxWidth = x
    }
    if (y > maxHeight) {
      maxHeight = y
    }
  })
  return { width: maxWidth - minWidth, height: maxHeight - minHeight }
}

export function getVerticesFromRect({ width, height }: Rect): Vertices {
  const w = width, h = height
  return [
    [0, 0],
    [w, 0],
    [w, 0],
    [w, h],
    [w, h],
    [0, h],
    [0, h],
    [0, 0],
  ]
}

export function percentage(val: number) {
  return round(val * 100, 2) + '%'
}